package com.joolun.mall.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joolun.common.core.domain.entity.SysDictData;
import com.joolun.common.exception.CustomException;
import com.joolun.common.utils.SecurityUtils;
import com.joolun.common.utils.StringUtils;
import com.joolun.mall.constant.DicType;
import com.joolun.mall.domain.vo.ChainTbWdtRelError;
import com.joolun.mall.entity.Brand;
import com.joolun.mall.entity.ChainPlanReserveOrder;
import com.joolun.mall.entity.ChainTbWdtRel;
import com.joolun.mall.mapper.BrandMapper;
import com.joolun.mall.mapper.ChainTbWdtRelMapper;
import com.joolun.mall.service.IChainTbWdtRelService;
import com.joolun.system.mapper.SysDictDataMapper;
import com.joolun.system.service.ISysDictDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 淘宝旺店通关联关系
 * 
 * @author www.joolun.com
 * @date 2025-05-20
 */
@Service
public class ChainTbWdtRelServiceImpl extends ServiceImpl<ChainTbWdtRelMapper, ChainTbWdtRel> implements IChainTbWdtRelService {

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ISysDictDataService dictDataService;


    @Override
    public boolean add(ChainTbWdtRel dto) {
        if(StringUtils.isEmpty(dto.getTbUserId()) || StringUtils.isEmpty(dto.getWdtEncodeUserId())){
            throw new CustomException("淘宝账号或旺店通加密id不能为空");
        }
        if(Objects.isNull(dto.getBrandId()) ){
            throw new CustomException("品牌不能为空");
        }
        Brand brand = brandMapper.selectOne(Wrappers.<Brand>lambdaQuery()
                .eq(Brand::getState, 1L)
                .eq(Brand::getIsDelete, 0L)
                .eq(Brand::getTenantId, 1L)
                .eq(Brand::getBrandId, dto.getBrandId())
                .orderByAsc(Brand::getSort));

        if(checkTbUserIdAndWdtId(dto)){
            throw new CustomException("淘宝账号或旺店通加密id已存在");
        }

        Map<String, SysDictData> vipMap = dictDataService.getDictData(DicType.DICT_TYPE_VIP_TYPE);
        if(!vipMap.containsKey(dto.getVipType())){
            throw new CustomException("VIP等级不存在");
        }
        dto.setVipTypeValue(vipMap.get(dto.getVipType()).getDictLabel());
        dto.setBrandName(brand.getBrandName());
        checkRepeat(dto,1);
        dto.setCreateBy(SecurityUtils.getUsername());
        dto.setCreateTime(new Date());
        return super.save(dto);
    }

    /**
     * 校验淘宝账号或旺店通加密id是否已存在
     * @param dto
     * @return true 存在 false 不存在
     */
    private boolean checkTbUserIdAndWdtId(ChainTbWdtRel dto) {
        List<ChainTbWdtRel> tbWdtRels = baseMapper.selectList(Wrappers.<ChainTbWdtRel>lambdaQuery()
                .eq(ChainTbWdtRel::getDelFlag, "0")
                .eq(ChainTbWdtRel::getBrandId, dto.getBrandId())
                .and(e ->
                        e.eq(ChainTbWdtRel::getTbUserId, dto.getTbUserId())
                                .or().eq(ChainTbWdtRel::getWdtEncodeUserId, dto.getWdtEncodeUserId()
                                )
                ));
        return CollectionUtil.isNotEmpty(tbWdtRels);
    }

    /**
     *
     * @param entity
     * @param operType 1:新增 2:修改
     */
    private void checkRepeat(ChainTbWdtRel entity,Integer operType) {

        // 一、 校验账号唯一
        List<ChainTbWdtRel> relations =  baseMapper.selectList(
                Wrappers.<ChainTbWdtRel>lambdaQuery()
                        .and(
                                e-> e.eq(ChainTbWdtRel::getTbUserId, entity.getTbUserId())
                                        .or()
                                        .eq(ChainTbWdtRel::getWdtEncodeUserId, entity.getWdtEncodeUserId())
                        )
                        .eq(ChainTbWdtRel::getDelFlag, "0")
        );

        if(operType == 1){
            relations.add(entity);
        }
        Map<String, List<ChainTbWdtRel>> chainTbWdtRelGroup = relations.stream().collect(Collectors.groupingBy(e -> e.getTbUserId() + "+" + e.getWdtEncodeUserId()));

        if(chainTbWdtRelGroup.size() > 1){
            throw new CustomException("淘宝账号或旺店通加密id重复: " + entity.getTbUserId() + " -> " + entity.getWdtEncodeUserId());
        }


        // 二、 校验品牌下唯一
        List<ChainTbWdtRel> chainTbWdtRels =  baseMapper.selectList(
                    Wrappers.<ChainTbWdtRel>lambdaQuery()
                            .eq(ChainTbWdtRel::getBrandId, entity.getBrandId())
                            .and(
                                    e-> e.eq(ChainTbWdtRel::getTbUserId, entity.getTbUserId())
                                            .or()
                                            .eq(ChainTbWdtRel::getWdtEncodeUserId, entity.getWdtEncodeUserId())
                            )
                            .eq(ChainTbWdtRel::getDelFlag, "0")
        );

        if(operType == 1){
            chainTbWdtRels.add(entity);
        }
        Map<String, List<ChainTbWdtRel>> brandGroup = chainTbWdtRels.stream().collect(Collectors.groupingBy(e -> e.getTbUserId() + "-" + e.getWdtEncodeUserId() + "-" + e.getBrandId()));
        brandGroup.forEach((k,v)->{
            if(v.size() > 1){
                throw new CustomException("淘宝账号或旺店通加密id重复: " + entity.getTbUserId() + " -> " + entity.getWdtEncodeUserId() + " -> " + entity.getBrandName());
            }
        });
    }

    @Transactional
    @Override
    public List<ChainTbWdtRelError> importData(List<ChainTbWdtRel> datas) {
        List<ChainTbWdtRelError> errors = new ArrayList<>();

        List<Brand> brands = brandMapper.selectList(Wrappers.<Brand>lambdaQuery()
                .eq(Brand::getState, 1L)
                .eq(Brand::getIsDelete, 0L)
                .eq(Brand::getTenantId, 1L)
                .orderByAsc(Brand::getSort));

        Map<String,Integer> brandMap = brands.stream().collect(Collectors.toMap(Brand::getBrandName, Brand::getBrandId));
        Map<String, SysDictData> vipMap = dictDataService.getDictData(DicType.DICT_TYPE_VIP_TYPE);
        Map<String, String> vipValueKeyMap = new HashMap<>();
        vipMap.values().forEach(e -> vipValueKeyMap.put(e.getDictLabel(), e.getDictValue()));


        for (ChainTbWdtRel dto : datas) {
            ChainTbWdtRelError errorVo = new ChainTbWdtRelError();
            BeanUtils.copyProperties(dto, errorVo);
            dto.setBrandId(brandMap.get(dto.getBrandName()));
            if(Objects.isNull(dto.getBrandId()) ){
                errorVo.setError(errorVo.getError() + "品牌为空或品牌不正确 ");
                errors.add(errorVo);
                continue;
            }

            if(StringUtils.isEmpty(dto.getTbUserId()) || StringUtils.isEmpty(dto.getWdtEncodeUserId())){
                errorVo.setError(errorVo.getError() + "淘宝账号或旺店通加密id不能为空 ");
                errors.add(errorVo);
                continue;
            }

            if(checkTbUserIdAndWdtId(dto)){
                errorVo.setError(errorVo.getError() + "淘宝账号或旺店通加密id已存在 ");
                errors.add(errorVo);
                continue;
            }


            if(!vipValueKeyMap.containsKey(dto.getVipTypeValue())){
                errorVo.setError(errorVo.getError() + "VIP等级不存在 ");
                errors.add(errorVo);
                continue;
            }
            dto.setVipType(vipValueKeyMap.get(dto.getVipTypeValue()));
            dto.setCreateBy(SecurityUtils.getUsername());
            dto.setCreateTime(new Date());



            if(StringUtils.isNotEmpty(errorVo.getError())){
                errors.add(errorVo);
            }else{
                super.save(dto);
            }
        }
        return errors;
    }

    @Override
    public void updateInfo(ChainTbWdtRel dto) {
        dto.setUpdateBy(SecurityUtils.getUsername());
        dto.setUpdateTime(new Date());

        Brand brand = brandMapper.selectOne(Wrappers.<Brand>lambdaQuery()
                .eq(Brand::getState, 1L)
                .eq(Brand::getIsDelete, 0L)
                .eq(Brand::getTenantId, 1L)
                .eq(Brand::getBrandId, dto.getBrandId())
                .orderByAsc(Brand::getSort));

        Map<String, SysDictData> vipMap = dictDataService.getDictData(DicType.DICT_TYPE_VIP_TYPE);
        if(!vipMap.containsKey(dto.getVipType())){
            throw new CustomException("VIP等级不存在");
        }
        dto.setVipTypeValue(vipMap.get(dto.getVipType()).getDictLabel());

        dto.setBrandName(brand.getBrandName());
        this.updateById(dto);
        this.checkRepeat(dto,2);
    }

}
